<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择订单类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源" prop="terminal">
        <el-select v-model="formData.terminal" placeholder="请选择订单来源">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员ID" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入会员ID" />
      </el-form-item>
      <el-form-item label="会员ip" prop="userIp">
        <el-input v-model="formData.userIp" placeholder="请输入会员ip" />
      </el-form-item>
      <el-form-item label="会员备注" prop="userRemark">
        <el-input v-model="formData.userRemark" type="textarea" placeholder="请输入会员备注" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择订单状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="代理人ID" prop="proxyUserId">
        <el-input v-model="formData.proxyUserId" placeholder="请输入代理人ID" />
      </el-form-item>
      <el-form-item label="购物车编号" prop="cartNo">
        <el-input v-model="formData.cartNo" placeholder="请输入购物车编号" />
      </el-form-item>
      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker
          v-model="formData.finishTime"
          type="date"
          value-format="x"
          placeholder="选择完成时间"
        />
      </el-form-item>
      <el-form-item label="取消时间" prop="cancelTime">
        <el-date-picker
          v-model="formData.cancelTime"
          type="date"
          value-format="x"
          placeholder="选择取消时间"
        />
      </el-form-item>
      <el-form-item label="取消类型" prop="cancelType">
        <el-select v-model="formData.cancelType" placeholder="请选择取消类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_CANCEL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="支付订单ID" prop="payOrderId">
        <el-input v-model="formData.payOrderId" placeholder="请输入支付订单ID" />
      </el-form-item>
      <el-form-item label="是否支付" prop="payStatus">
        <el-radio-group v-model="formData.payStatus">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker
          v-model="formData.payTime"
          type="date"
          value-format="x"
          placeholder="选择支付时间"
        />
      </el-form-item>
      <el-form-item label="支付渠道" prop="payChannelCode">
        <el-input v-model="formData.payChannelCode" placeholder="请输入支付渠道" />
      </el-form-item>
      <el-form-item label="原价(分)" prop="totalPrice">
        <el-input v-model="formData.totalPrice" placeholder="请输入原价(分)" />
      </el-form-item>
      <el-form-item label="优惠金额(分)" prop="discountPrice">
        <el-input v-model="formData.discountPrice" placeholder="请输入优惠金额(分)" />
      </el-form-item>
      <el-form-item label="调价（正加，负减）" prop="adjustPrice">
        <el-input v-model="formData.adjustPrice" placeholder="请输入调价（正加，负减）" />
      </el-form-item>
      <el-form-item label="应付金额" prop="payPrice">
        <el-input v-model="formData.payPrice" placeholder="请输入应付金额" />
      </el-form-item>
      <el-form-item label="退款类型" prop="refundType">
        <el-select v-model="formData.refundType" placeholder="请选择退款类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_REFUND_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款金额" prop="refundPrice">
        <el-input v-model="formData.refundPrice" placeholder="请输入退款金额" />
      </el-form-item>
      <el-form-item label="使用积分" prop="usePoint">
        <el-input v-model="formData.usePoint" placeholder="请输入使用积分" />
      </el-form-item>
      <el-form-item label="积分抵扣金额(分)" prop="pointPrice">
        <el-input v-model="formData.pointPrice" placeholder="请输入积分抵扣金额(分)" />
      </el-form-item>
      <el-form-item label="赠送积分" prop="givePoint">
        <el-input v-model="formData.givePoint" placeholder="请输入赠送积分" />
      </el-form-item>
      <el-form-item label="退款退还积分" prop="refundPoint">
        <el-input v-model="formData.refundPoint" placeholder="请输入退款退还积分" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { TradeOrderApi, TradeOrderVO } from '@/api/package/trade/order/tradeorder'

/** Saas订单 表单 */
defineOptions({ name: 'TradeOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  type: undefined,
  terminal: undefined,
  userId: undefined,
  userIp: undefined,
  userRemark: undefined,
  status: undefined,
  proxyUserId: undefined,
  cartNo: undefined,
  finishTime: undefined,
  cancelTime: undefined,
  cancelType: undefined,
  remark: undefined,
  payOrderId: undefined,
  payStatus: undefined,
  payTime: undefined,
  payChannelCode: undefined,
  totalPrice: undefined,
  discountPrice: undefined,
  adjustPrice: undefined,
  payPrice: undefined,
  refundType: undefined,
  refundPrice: undefined,
  usePoint: undefined,
  pointPrice: undefined,
  givePoint: undefined,
  refundPoint: undefined
})
const formRules = reactive({
  type: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
  cartNo: [{ required: true, message: '购物车编号不能为空', trigger: 'blur' }],
  totalPrice: [{ required: true, message: '原价(分)不能为空', trigger: 'blur' }],
  discountPrice: [{ required: true, message: '优惠金额(分)不能为空', trigger: 'blur' }],
  adjustPrice: [{ required: true, message: '调价（正加，负减）不能为空', trigger: 'blur' }],
  payPrice: [{ required: true, message: '应付金额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TradeOrderApi.getTradeOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TradeOrderVO
    if (formType.value === 'create') {
      await TradeOrderApi.createTradeOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await TradeOrderApi.updateTradeOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    type: undefined,
    terminal: undefined,
    userId: undefined,
    userIp: undefined,
    userRemark: undefined,
    status: undefined,
    proxyUserId: undefined,
    cartNo: undefined,
    finishTime: undefined,
    cancelTime: undefined,
    cancelType: undefined,
    remark: undefined,
    payOrderId: undefined,
    payStatus: undefined,
    payTime: undefined,
    payChannelCode: undefined,
    totalPrice: undefined,
    discountPrice: undefined,
    adjustPrice: undefined,
    payPrice: undefined,
    refundType: undefined,
    refundPrice: undefined,
    usePoint: undefined,
    pointPrice: undefined,
    givePoint: undefined,
    refundPoint: undefined
  }
  formRef.value?.resetFields()
}
</script>